{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "ComputerVisionForBeginner.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "metadata": {
        "id": "ejO-t858Fw8g",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "\n",
        "# Computer Vision for beginner\n",
        "\n",
        "---\n",
        "\n",
        "![Computer vision](https://i.ibb.co/bLqmR3H/CV.jpg)\n",
        "\n",
        "In this guide, we will discuss the purpose of Computer Vision in Python. We will learn how to handle data with OpenCV libraries by displaying and creating images. We will also see the process of detecting edges and faces.  \n",
        "\n",
        "## What is Computer Vision?\n",
        "\n",
        "Computer Vision is a multidisciplinary expertise that focuses on how computers can achieve a high-level of knowledge from visual data (like images, videos). In this way, we are trying to ensure that the tasks that the human brain is able to perform are automatically executed. It is a process of acquiring, processing, analyzing and understanding a large amount of visual and symbolic information from the real world.\n",
        "\n",
        "- The common tasks involved in using Computer Vision are the following: *Recognition, Motion analysis, Scene Reconstruction, Image retrieval, and so on*;\n",
        "- Fields linked to Computer Vision include: *Artificial Intelligence, Neurobiology, Signal Processing, Statistics, Optimization, and so on.*;\n",
        "- A number of Computer Vision applications include: *Control Processes, Events Detection, Autonomous Navigation, Object  Modeling, Indexation, and so on.*\n",
        "\n",
        "Useful books for learning various aspects of Computer Vision: [Multiple View Geometry in Computer Vision](http://www.robots.ox.ac.uk/~vgg/hzbook/),  [Computer Vision: Algorithms and Applications](http://szeliski.org/Book/)\n",
        "\n",
        "## Prerequisites\n",
        "\n",
        "It is essential to learn about *Python programming *and to familiarize yourself a little bit with the concepts of *image processing* before you take part in this guide.\n",
        "\n",
        "## Guide plan\n",
        "We will provide a structured content according to the following plan:\n",
        "\n",
        "Computer Vision with OpenCV and Python: \n",
        "1.    Install OpenCV in Python;\n",
        "2.   Import OpenCV in Python;\n",
        "3.   Deal with images in Python: Reading, Displaying, Creating images,  Edges and Faces detection.\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "## Computer Vision with OpenCV and Python\n",
        "\n",
        "[Gary Bradsky ](https://en.wikipedia.org/wiki/Gary_Bradski)started OpenCV at Intel in 1999. Compatible with a variety of languages such as C++, Python, etc., OpenCV-Python is an API that allows OpenCV to simultaneously release the power of Python and C++ API.\n",
        "In the case of Python, it is a library of binaries intended to address computer vision challenges. This library is based on NumPy and its array structures. That means we can also integrate it easily into other libraries such as SciPy and Matplotlib.\n",
        "\n",
        "### Install OpenCV in Python\n",
        "\n",
        "In order to install OpenCV, make sure that Python and NumPy have been installed on your PC.\n",
        "To avoid running into a DLL hell, it is possible to download the OpenCV [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv)\n",
        "Next, you may install that file using `pip` command:"
      ]
    },
    {
      "metadata": {
        "id": "2xb7UuSaJMCN",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "pip install [path_of_file]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "2MDN3mbmJNGH",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Import OpenCV in Python\n",
        "\n",
        "Open the IDLE and import OpenCV:"
      ]
    },
    {
      "metadata": {
        "id": "wUkhaiyMJWFo",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        " import cv2"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "cENZJo2WJYIh",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Alternatively, you can also check which version you have:"
      ]
    },
    {
      "metadata": {
        "id": "SQOHmC2zJZzO",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "cv2 .__ version__"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "nBt3gBllJbIl",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Deal with images in Python\n",
        "\n",
        "\n",
        "Now we have successfully installed OpenCV, let's start by doing it.\n",
        "\n",
        "**1.\tReading images in Python**\n",
        "\n",
        "To read an image, we have the `imread ()` function. It should be mentioned that previously, we have moved to the directory that contains the image."
      ]
    },
    {
      "metadata": {
        "id": "scMV3Gd1KOHN",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "img = cv2.imread ('img.jpg')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "0M1S9KvtKS0m",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "As an alternative, it is also possible to pass a value for a flag, which is the second argument\n",
        "\n",
        "- `cv2.IMREAD_COLOR`: For loading a color image by overlooking existing transparency; \n",
        "- `cv2.IMREAD_GRAYSCALE`: For loading a grayscale image;\n",
        "- `cv2.IMREAD_UNCHANGED`: For loading an image that includes an alpha channel\n",
        "\n",
        "It is possible to use integers 1, 0 or -1:\n"
      ]
    },
    {
      "metadata": {
        "id": "brJrg7QaKkxe",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "img = cv2. imread ('img.jpg', 0)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "TeU60Ds7KoT1",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Note that sending an invalid image path does not result in any errors.\n",
        "\n",
        "**2.\tDisplaying images in Python**\n",
        "\n",
        "The `cv2.imshow ()` function enables to display an image in a frame that can be adjusted to its size. The first argument is the name of the frame and the second one is the image.\n"
      ]
    },
    {
      "metadata": {
        "id": "9sPzKm5UK3lm",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "img = cv2. imread ('img.jpg')\n",
        "cv2.imshow('Images', img)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "-uN2JP8fLAqm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Note that we have two frames at once as we have not attempted to title them in the same way.\n",
        "`cv2.destroyAllWindows ()` is another function that destroys all the frames that we have already created. `cv2.destroyWindow () `also destroys a specific frame.\n",
        "\n",
        "**3.\tCreating images in Python**\n",
        "\n",
        "To do this, there is the `cv2. imwrite ()` function. The first argument is the file name and the second one is the image to be saved.\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "IeY5J7XOLVW_",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "cv2.imwrite('img_gray.png', img)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "hvbcXCeTLa-A",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "This will store the grayscale image named \"*img_gray.png*\" in the current location.  \n",
        "\n",
        "**4.\tDisplaying images using Matplotlib**\n",
        "\n",
        "By using [Matplotlib](https://matplotlib.org/index.html) library, we can display that image.\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "5RRDl2NbLqm4",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import matplotlib.pyplot as plt\n",
        "plt.imshow(img, cmap = \"gray\", interpolation = \"bilinear\")\n",
        "plt.xticks([]), pl.ticks ([])\n",
        "(([], ), ([], ))\n",
        "plt.display ()\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "UmSu0p_MMOSy",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "**5.\tCore operations on images**\n",
        "\n",
        "Let's now look at the basic operations applicable on the image.\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "7jabojv8Mi9F",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import cv2\n",
        "img = cv2.imread ('img.jpg')\n",
        "y, x = 100,50\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "MSH-HU4iMoM_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Reading of color values at positions y, x:"
      ]
    },
    {
      "metadata": {
        "id": "EKcQgXsJMrDv",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "(b, g, r) = img[y,x] "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ZRUEAR0BM1Am",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Setting the red pixel color:"
      ]
    },
    {
      "metadata": {
        "id": "BVHlOuwWM26J",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "img[y,x]= (0,0,255) "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "y66e4dfsM5jQ",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Printing color values on the screen"
      ]
    },
    {
      "metadata": {
        "id": "k0NIjucuMu-W",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "b, g, r "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "pUduk6iINIqY",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Region of interest at (x, y) whose dimensions are 100x100"
      ]
    },
    {
      "metadata": {
        "id": "O3CW6-0sNNTe",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "roi = img[y:y+100,x:x+100] \n",
        "cv2.imshow ('image', img)\n",
        "cv2.imshow('ROI', roi)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "73dsveRmNP6G",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Pixelization of the new color :"
      ]
    },
    {
      "metadata": {
        "id": "Oymttem1NZEW",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "roi[:,:]= (55,44,87) \n",
        "cv2.imshow('New image', img)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "nliblH8QNq5P",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "**6.\tEdge detection in Python**\n",
        "\n",
        "In OpenCV we can choose only to display the edges of objects with the `Canny () `function:"
      ]
    },
    {
      "metadata": {
        "id": "ZLz-dEqUNxT_",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "img = cv2.imread('img.jpg')\n",
        "cv2.imwrite ('edge_img.jpg', cv2.Canny (img, 512, 415))\n",
        "cv2.imshow ('edges', cv2.imread('edge_img.jpg'))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "sdVRPovsN0G-",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "**7.\tFace detection in Python**\n",
        "\n",
        "OpenCV will also enable to detect faces in images. Let's now use *Haar's cascading classifie*r. \n",
        "\n",
        "Now, there is one last point that we would really like to address, and that is the face detection. The Haar classifier is used. It is a matter of locating the position of faces in an image in order to standardize the size of the face area.  "
      ]
    },
    {
      "metadata": {
        "id": "s7Y4xPdCOnJK",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import sys, os\n",
        "import cv2\n",
        "  \n",
        "def face_detection(image, image_out, show = False):\n",
        "    # Load the image in memory\n",
        "    img = cv2.imread(image)\n",
        "    # Load the face detection model\n",
        "    face_model = cv2.CascadeClassifier(\"haarcascade_frontalface_alt2.xml\")\n",
        "     \n",
        "     \n",
        "    # detection of the face(s)\n",
        "    faces = face_model.detectMultiScale(img)\n",
        "     \n",
        "    # we place a bounding boxe around the faces\n",
        "    print (\"number of faces\", len(faces), \"image size\", img.shape, \"image\", image)\n",
        "    for face in faces:\n",
        "        cv2.rectangle(img, (face[0], face[1]), (face[0] + face[2], face[0] + face[3]), (255, 0, 0), 3)\n",
        "         \n",
        "    # we store the final result\n",
        "    cv2.imwrite(image_out, img)\n",
        "     \n",
        "    # to see the image, press ESC to exit\n",
        "    if show :\n",
        "        cv2.imshow(\"face\",img)\n",
        "        if cv2.waitKey(5000) == 27: cv2.destroyWindow(\"face\")\n",
        "   \n",
        "if __name__ == \"__main__\":\n",
        "    # wall lamp \n",
        "    for file in os.listdir(\".\"\") :\n",
        "        if file.startswith(\"face\") : continues # already processed\n",
        "        if os.path.splitext(file)[-1].lower() in [\".jpg\",\".jpeg\",\".png\" ] :\n",
        "            face_detect (file, \"face_\" + file)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Db9WcwAlPBT_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "As you can see, it drew a blue square (bounding boxe) around the face in the image.  "
      ]
    }
  ]
}
